﻿using Newtonsoft.Json;
using Ongoal.Quotation.Common;
using Ongoal.Quotation.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Net.Mime.MediaTypeNames;

namespace Ongoal.Quotation
{
    public static class ServiceHelper
    {
        private static string appInfoPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "sys", "appInfo.config");
        /// <summary>
        /// 获取Service ID（如果未配置Service ID，系统自动生成）
        /// </summary>
        /// <returns></returns>
        public static string GetServiceId()
        {
            if (!File.Exists(appInfoPath))
            {
                return GenerateServiceId();
            }
            else
            {
                var json = FileHelper.ReadString(appInfoPath);
                if (String.IsNullOrWhiteSpace(json))
                {
                    return GenerateServiceId();
                }

                try
                {
                    AppModel appModel = JsonConvert.DeserializeObject<AppModel>(json);
                    return appModel.ServiceId;
                }
                catch
                {
                    return GenerateServiceId();
                }

            }
        }

        /// <summary>
        /// 生成Service ID
        /// </summary>
        /// <returns></returns>
        internal static string GenerateServiceId()
        {
            AppModel appModel = new AppModel() { ServiceId = Guid.NewGuid().ToString(), ServiceDeploymentTime = DateTime.Now };
            string json = JsonConvert.SerializeObject(appModel);
            FileHelper.WriteString(appInfoPath, json);
            return appModel.ServiceId;
        }
    }
}
